package net.oschina.dajiangnan.wx.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import net.oschina.dajiangnan.wx.constants.Config;
import net.oschina.dajiangnan.wx.constants.Custom;
import net.oschina.dajiangnan.wx.constants.DynamicValue;
import net.oschina.dajiangnan.wx.constants.PathDefine;
import net.oschina.dajiangnan.wx.process.mp.Echo;
import net.oschina.dajiangnan.wx.process.mp.tools.Menu;
import net.oschina.dajiangnan.wx.process.msg.DisPatcher;
import net.oschina.dajiangnan.wx.process.pay.H5_pay;
import net.oschina.dajiangnan.wx.process.pay.Pay_notify;
import net.oschina.dajiangnan.wx.process.pay.Scan_qrcode_notify;

public class WxGateWay extends HttpServlet {

	private static final long serialVersionUID = 7505768091482992805L;

	private static Logger logger = Logger.getLogger(WxGateWay.class);

	@Override
	public void init(ServletConfig config) {
		try {
			Config.init(config);

			Custom.init(config);

			if (!StringUtils.isEmpty(Custom.wx.getMenuDesc())) {
				Menu.define(Custom.wx.getMenuDesc());
			}

			DynamicValue.startGet();

		} catch (Throwable t) {
			t.printStackTrace();
			logger.error(t);
		}
	}
	
	public void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
	    if(refuseIp(req,resp)) return;
	    super.service(req, resp);
	}

	@Override
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws IOException, ServletException {
	    
		String respContent = "";

		try {
			if (req.getRequestURI().endsWith(PathDefine.BASE_PATH + ".wx")) {
				respContent = new DisPatcher().disPatcher(req);
			}
			if (req.getRequestURI().endsWith(PathDefine.SCANQR_PATH + ".wx")) {
				respContent = new Scan_qrcode_notify().process(req);
			}
			if (req.getRequestURI().endsWith(PathDefine.PAYED_PATH + ".wx")) {
				respContent = new Pay_notify().process(req);
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e);
		}

		resp.setCharacterEncoding("utf-8");
		resp.setContentType("text/xml; charset=utf-8");
		PrintWriter out = resp.getWriter();
		out.print(respContent);
	}

	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException, ServletException {
	    
		String respContent = "";

		try {
			if (req.getRequestURI().endsWith(PathDefine.BASE_PATH + ".wx")) {
				respContent = new Echo().process(req);
			}
			if (req.getRequestURI().endsWith(PathDefine.H5_PAY_PATH + ".wx")) {
				respContent = new H5_pay().process(req, resp);
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e);
		}

		resp.setCharacterEncoding("utf-8");
		resp.setContentType("text/html; charset=utf-8");
		PrintWriter out = resp.getWriter();

		out.print(respContent);
	}

	
	
	private boolean refuseIp(HttpServletRequest req, HttpServletResponse resp){
	    String uri = req.getRequestURI();
	    if(uri.endsWith(PathDefine.BASE_PATH + ".wx")
	            ||req.getRequestURI().endsWith(PathDefine.SCANQR_PATH + ".wx")
	            ||req.getRequestURI().endsWith(PathDefine.PAYED_PATH + ".wx")
	            ||req.getRequestURI().endsWith(PathDefine.BASE_PATH + ".wx")
	            ){
	        //需要验证IP
	        String ip = req.getRemoteAddr();
	        if(DynamicValue.isAllowIp(ip)){
	            return false;
	        }else{
	            resp.setCharacterEncoding("utf-8");
	            resp.setContentType("text/html; charset=utf-8");
	            PrintWriter out;
	            try {
	                out = resp.getWriter();
	                out.print("refuse ip = " + ip);
	            } catch (IOException e) {
	                e.printStackTrace();
	            }           
	            return true;
	        }
	    }else{
	        return false;
	    }
	}
}
